import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/account/models/user_response.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class LocationSettingPageLogic extends ChangeNotifier {
  List<ChinaRegion>? regions;
  bool isLoading = false;
  bool isError = false;

  final String? code;
  final int level;
  final String? title;

  late final _cancelToken = CancelToken();

  LocationSettingPageLogic({
    required this.code,
    required this.level,
    required this.title,
  });

  String? _selectedCode;
  String? get selectedCode {
    if (_selectedCode != null) {
      return _selectedCode;
    }
    final index = level - 1;
    final areaCodeList = AccountInfo.shared.userProfile?.regionCodeList;
    if (areaCodeList != null && index < areaCodeList.length) {
      return areaCodeList[index];
    } else {
      return null;
    }
  }

  @override
  void dispose() {
    _cancelToken.cancel();
    super.dispose();
  }

  void init() {
    // 延迟加载
    // Future.delayed(Duration.zero, () {
    loadRegions();
    // });
  }

  void selectRegion(ChinaRegion region) {
    _selectedCode = region.code;
    notifyListeners();
  }

  // 更新地区
  Future<bool> updateRegion() async {
    final newCode = _selectedCode ?? code;
    if (newCode == null) {
      return true;
    }
    // 数据未改变
    if (AccountInfo.shared.userProfile?.regionCodeList?.last == newCode) {
      return true;
    }

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      final response = await DataFetcher.shared.userApi.updateUserRegion(
        newCode,
      );
      EasyLoading.dismiss();
      if (response.code == 0 && response.result?.field == 'region') {
        EasyLoading.showSuccess(AppStrings.updateSuccess);
        AccountInfo.shared.updateRegion(
          response.result?.value,
          response.result?.list,
        );
        return true;
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
        return false;
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('${AppStrings.updateError}: $e');
      return false;
    }
  }

  // 加载地区列表
  void loadRegions() async {
    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      isLoading = true;
      isError = false;
      notifyListeners();

      final response = await DataFetcher.shared.userApi.getChinaRegions(
        code: code,
        cancelToken: _cancelToken,
      );
      isLoading = false;
      EasyLoading.dismiss();
      if (response.code == 0 && response.regions != null) {
        regions = response.regions;
      } else if (response.code != 0) {
        isError = true;
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
      }
      notifyListeners();
    } on DioException catch (e) {
      EasyLoading.dismiss();
      // 请求被取消
      if (e.type == DioExceptionType.cancel) {
        log('Request cancelled:${e.message}');
        return;
      }
      isLoading = false;
      isError = true;
      notifyListeners();
      EasyLoading.showError(e.toString());
    } catch (e) {
      log('${AppStrings.queryRegionError}: $e');
    }
  }
}
